package com.atguigu.gmall.common.service.impl;

import com.atguigu.gmall.common.properties.MinioProperties;
import com.atguigu.gmall.common.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties ;

    @Autowired
    private MinioClient minioClient ;

    @Override
    public String fileUpload(MultipartFile multipartFile) {

        try {

            // 判断桶是否存在，如果不存在，那么就创建一个桶
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build());
            if (!found) {        // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
            }

            // 上传文件
            String originalFilename = multipartFile.getOriginalFilename();      // 获取原始的文件名称  yiuywiueyruere.jpg
            String extName = FilenameUtils.getExtension(originalFilename);
            String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extName;
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName)
                    .stream(multipartFile.getInputStream() , multipartFile.getSize() , -1)
                    .build();
            minioClient.putObject(putObjectArgs) ;

            // 文件的访问路径
            String imgeUrl = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + fileName ;
            return imgeUrl ;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
